import json

from fastapi import APIRouter
from re_common.baselibrary.tools.all_requests.aiohttp_request import AioHttpRequest
from re_common.baselibrary.tools.all_requests.mrequest import MRequest
from re_common.baselibrary.utils.core.mlamada import bools_string

from apps.allsubdb.paper_grrb.models import json_header
from apps.core.global_model import IdMarksModel
from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import InputInfoModel, ReturnInfo

router = APIRouter(route_class=ContextIncludedRoute)


@router.post("/step2/get_one_days")
async def get_page_link(input: InputInfoModel[IdMarksModel]):
    """
    获取某一天的报纸，可以直接通过拼接 <br>
    http://media.workercn.cn/sites/paper/paper_index.html?type=grrb&date=2020-12-29 <br>
    下载回来的json中包含所有的数据 不需要下载版和文章 <br>
    marks： ["paperHomeUrl"]  <br>
    :param input: <br>
    :return: <br>
    """
    return_info = ReturnInfo()
    proxy = input.proxy
    # 任意日期的url都会在最新的年月
    date = input.data.id  # 为日期
    marks = input.data.marks
    year = date[0:4]
    month = date[4:6]
    days = date[-2:]
    # 实际数据的url
    url = f"http://i.workercn.cn/paper/grrb/{year}/{month}/{days}.json"
    # this_header = json_header.copy()
    rrq = AioHttpRequest()
    rrq.set_url(url) \
        .set_timeout(30).set_marks(marks) \
        .set_proxy(proxy) \
        .set_middler_list(
        [rrq.status_code_middlerwares, rrq.marks_middlerwares, rrq.is_json_middlerwares])
    bools, dicts = await rrq.run(MRequest.GET)
    if bools:
        dicts_data = json.loads(rrq.html)
        stat = 1
        if len(dicts_data["pages"]) == 0:
            stat = -1  # 代表当天没有数据，如果某个月都没有数据代表结束
        return_info.status = bools_string(bools)
        return_info.msg_code = dicts["code"]
        return_info.msg = dicts["msg"]
        return_info.data = {"html": rrq.html, "stat": stat, "json_url": url}
        return return_info.todict()
    else:
        return_info.status = bools_string(bools)
        return_info.msg_code = dicts["code"]
        return_info.msg = dicts["msg"]
        if return_info.msg_code == 404:
            return_info.data = {"html": rrq.html, "stat": -1, "json_url": url}
            return return_info.todict()
        elif return_info.msg_code == 211:
            return_info.data = {"html": rrq.html, "stat": -2, "json_url": url}
            return return_info.todict()
        else:
            return_info.data = {"html": rrq.html, "stat": 0, "json_url": url}
            return return_info.todict()
